<template>
  <a-modal
    :open="open"
    title="Write a Review"
    @cancel="handleCancel"
    @ok="handleSubmit"
    :confirmLoading="loading"
    :width="modalWidth"
    class="review-modal-container"
    :maskClosable="true"
    :destroyOnClose="true"
  >
    <a-form
      :model="form"
      :rules="rules"
      ref="formRef"
      class="review-form-container"
    >
      <a-form-item name="score" label="Rating" :rules="[{ required: true, message: 'Please rate this product!' }]">
        <a-rate v-model:value="form.score" class="review-rate" />
      </a-form-item>
      
      <a-form-item name="content" label="Review" :rules="[{ required: true, message: 'Please write your review!' }]">
        <a-textarea 
          v-model:value="form.content" 
          placeholder="Share your experience with this product" 
          :rows="4"
          class="review-textarea" 
        />
      </a-form-item>
      
      <a-form-item label="Upload Images (Max 9)" class="review-upload-container">
        <a-upload
          v-model:fileList="fileList"
          list-type="picture-card"
          :before-upload="beforeUpload"
          @remove="handleRemove"
          :maxCount="9"
          class="review-upload"
        >
          <div v-if="fileList.length < 9">
            <plus-outlined />
            <div style="margin-top: 8px">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal :open="previewVisible" :footer="null" @cancel="previewVisible = false">
    <img alt="Preview Image" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted, onBeforeUnmount } from 'vue';
import { message, Upload } from 'ant-design-vue';
import { PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  orderId: {
    type: [Number, String],
    default: ''
  },
  detailId: {
    type: [Number, String],
    default: ''
  }
});

const emit = defineEmits(['update:open', 'submit']);

const formRef = ref(null);
const loading = ref(false);
const fileList = ref([]);
const previewVisible = ref(false);
const previewImage = ref('');

const form = reactive({
  order_id: props.orderId,
  detail_id: props.detailId,
  score: 0,
  content: '',
  images: ''
});

const rules = {
  score: [
    { required: true, message: 'Please rate the product', trigger: 'change' }
  ],
  content: [
    { required: true, message: 'Please enter review content', trigger: 'blur' },
    { min: 10, message: 'Content should be at least 10 characters', trigger: 'blur' }
  ],
};

const handleCancel = () => {
  emit('update:open', false);
  formRef.value?.resetFields();
  fileList.value = [];
};

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('You can only upload image files!');
    return Upload.LIST_IGNORE;
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('Image must be smaller than 2MB!');
    return Upload.LIST_IGNORE;
  }
  
  // 直接读取文件为 Base64
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      file.base64 = event.target.result;
      resolve(file);
    };
    reader.readAsDataURL(file);
  });
};

const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
};

const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};

const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;
    
    // 处理图片数据，转换为逗号分隔的 Base64 字符串
    if (fileList.value.length > 0) {
      form.images = fileList.value
        .map(file => file.base64)
        .join(',');
    }
    
    // 发送数据到父组件
    emit('submit', { ...form });
    
    // 清空表单
    formRef.value.resetFields();
    fileList.value = [];
    loading.value = false;
    
    // 关闭弹窗
    emit('update:open', false);
  } catch (error) {
    loading.value = false;
    console.error('Validation failed:', error);
  }
};

watch(() => props.orderId, (newVal) => {
  form.order_id = newVal;
});

watch(() => props.detailId, (newVal) => {
  form.detail_id = newVal;
});

watch(() => props.open, (newVal) => {
  if (!newVal) {
    handleCancel();
  }
});

// Add window width tracking
const windowWidth = ref(window.innerWidth);
const modalWidth = computed(() => {
  if (windowWidth.value <= 576) {
    return '95%';
  } else if (windowWidth.value <= 768) {
    return '85%';
  } else {
    return '600px';
  }
});

// Add window resize handler
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.review-modal-container {
  width: 100%;
  max-width: 100%;
}

.review-form-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
  margin-bottom: 20px;
}

.review-rate {
  font-size: 28px;
}

.review-textarea {
  width: 100%;
  resize: vertical;
}

.review-upload-container {
  margin-bottom: 0;
}

.review-upload :deep(.ant-upload-list-item) {
  width: 100px;
  height: 100px;
  margin-right: 8px;
  margin-bottom: 8px;
}

/* Responsive styles */
@media (max-width: 768px) {
  .review-modal-container :deep(.ant-modal-content) {
    width: 100%;
    margin: 0;
    padding: 16px;
  }
  
  .review-modal-container :deep(.ant-modal-body) {
    padding: 12px;
  }
  
  .review-rate {
    font-size: 24px;
  }
  
  .review-form-container {
    max-height: 70vh;
  }
  
  .review-upload :deep(.ant-upload-list-item) {
    width: 80px;
    height: 80px;
    margin-right: 6px;
    margin-bottom: 6px;
  }
  
  .review-modal-container :deep(.ant-modal-close) {
    width: 36px;
    height: 36px;
    z-index: 999;
  }
  
  /* Add custom styles for footer buttons to make them more accessible */
  .review-modal-container :deep(.ant-modal-footer .ant-btn) {
    height: 40px;
    font-size: 14px;
    min-width: 80px;
  }
}

@media (max-width: 576px) {
  .review-modal-container :deep(.ant-modal) {
    max-width: 100% !important;
    margin: 0;
    top: 0;
  }
  
  .review-modal-container :deep(.ant-modal-content) {
    border-radius: 0;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  .review-modal-container :deep(.ant-modal-body) {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
  }
  
  .review-form-container {
    max-height: calc(100vh - 120px);
    overflow-y: auto;
  }
  
  .review-modal-container :deep(.ant-modal-footer) {
    border-top: 1px solid #f0f0f0;
    padding: 10px 16px;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .review-modal-container :deep(.ant-modal-close) {
    position: fixed;
    z-index: 1001;
    background: rgba(255, 255, 255, 0.9);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
  
  .review-rate {
    font-size: 22px;
  }
  
  .review-form-container {
    max-height: 60vh;
    padding-right: 5px;
  }
  
  .review-upload :deep(.ant-upload-list-item),
  .review-upload :deep(.ant-upload-select) {
    width: 70px !important;
    height: 70px !important;
    margin-right: 4px;
    margin-bottom: 4px;
  }
}

/* Improved close button styles */
:deep(.ant-modal-close) {
  padding: 8px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  width: 36px;
  height: 36px;
  top: 8px;
  right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-modal-close-x) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 16px;
}
</style> 